/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DigestControllers;

import DigestModels.Database;
import DigestViews.LoginView;
import DigestViews.MainView;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author Prophet,Sheamus,Israel
 */
public class LoginController {

    Database db;
    ActionListener actionListener;
    MainView mv;
    LoginView lg;

    /**
     * Constructor
     *
     * @param db
     * @param lg
     */
    public LoginController(Database db, LoginView lg) {
        this.db = db;
        this.lg = lg;
        if (!db.initComponents()) {
            JOptionPane.showMessageDialog(lg, "Please connect the database and restart the program.");
            System.exit(0);
        }

    }

    /**
     * This method initiates the listeners.
     */
    public void control() {
        actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == lg.getLoginBtn()) {
                    login();
                } else if (e.getSource() == lg.getExitBtn()) {
                    lg.dispose();
                }
            }
        };

        lg.getLoginBtn().addActionListener(actionListener);
        lg.getExitBtn().addActionListener(actionListener);

    }

    /**
     * This method executes the login
     */
    public void login() {
        JTextField userName = lg.getUsername();
        JPasswordField passField = lg.getPassword();
        char[] p = passField.getPassword();
        String pass = "";
        for (int i = 0; i < p.length; i++) {
            pass = pass + p[i];
        }
        if (db.checkPassword(userName.getText(), pass)) {
            lg.dispose();
            mv = new MainView();
            MainViewController mc = new MainViewController(mv, db, lg);
            mc.control();
        } else //System.out.println("Login is failed");
        {
            JOptionPane.showMessageDialog(lg, "Login Failed");
        }
    }

}
